import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanxiang_app/bean/bind_account_entity.dart';
import 'package:wanxiang_app/bean/simple_entity.dart';
import 'package:wanxiang_app/utils/common.dart';
import 'package:wanxiang_app/utils/constant.dart';
import 'package:wanxiang_app/widgets/money_textField.dart';
import '../../bean/login_entity.dart';
import '../../bean/registe_entity.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../utils/user_util.dart';
import '../../widgets/account_textField2.dart';
import '../../widgets/myappbar.dart';
import 'package:get/get.dart';
import 'package:tobias/tobias.dart' ;

import '../../widgets/simple_dialog.dart';
class PayController extends GetxController{


  String price = '';
  Map payMap = {};
  bool inputEnable = false;
  @override
  void onInit() {
    super.onInit();
    _getUserBinding();
    _getInfo();
  }

  @override
  void onClose() {
    super.onClose();
  }

  String zfb_num = '';
  String bank_card = '';
  String bank_name = '';
  String id_card = '';
  String name = '';

  String zfb = '';
  String bank = '';
  String psw = '';
  String mobile =  UserUtil.getUSER()!.mobile;
  void _getUserBinding(){
    DioManager.getInstance().post(ServiceUrl.getUserBinding,{
      "user_name":UserUtil.getUSER()?.userName.toString(),
    }, (data) async {
      BindAccountEntity bannerEntity = BindAccountEntity.fromJson(jsonDecode(data));
      if(bannerEntity.code==200){
        zfb='';
        bank='';
        for(var item in bannerEntity.data){
          if(item.bindingType == '2'){// 支付宝
            zfb =item.zfbNum;
          }else  if(item.bindingType == '3'){// 支付宝
            bank = item.bankCard;
          }
        }
        update();
      }else{

      }
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _bindAlipay(){
    DioManager.getInstance().post(ServiceUrl.getAddBinding,{
      "binding_type":'2',
      "name":name,
      "id_card":id_card,
      "zfb_num":zfb_num,
      "user_name":UserUtil.getUSER()?.userName.toString(),
    }, (data) async {
      BindAccountEntity bannerEntity = BindAccountEntity.fromJson(jsonDecode(data));
      ToastUtil.show(bannerEntity.msg);
      if(bannerEntity.code==200){
        _getUserBinding();
      }else{

      }
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _bindBank(){
    DioManager.getInstance().post(ServiceUrl.getAddBinding,{
      "binding_type":'3',
      "bank_card":bank_card,
      "bank_name":bank_name,
      "name":name,
      "id_card":id_card,
      "user_name":UserUtil.getUSER()?.userName.toString(),
    }, (data) async {
      BindAccountEntity bannerEntity = BindAccountEntity.fromJson(jsonDecode(data));
      ToastUtil.show(bannerEntity.msg);
      if(bannerEntity.code==200){
        _getUserBinding();
      }else{

      }
    }, (error) {
      ToastUtil.show(error);
    });
  }

  bool isPsw = false;

  _getInfo() {
    DioManager.getInstance().post(ServiceUrl.myInfo,{
      "user_name":UserUtil.getUSER()?.userName
    }, (data1) async {
      LoginEntity  entity = LoginEntity.fromJson(jsonDecode(data1));
      if(entity.data.withdrawPw.isEmpty){
        isPsw = false;
      }else{
        isPsw = true;
      }
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _bindPsw(){
    if (mobile.isEmpty) {
      ToastUtil.show('请正确输入手机号');
      return;
    }

    if (code.isEmpty) {
      ToastUtil.show('请输入验证码');
      return;
    }

    if (psw.isEmpty || psw.length < 6 || psw.length > 16) {
      ToastUtil.show('请正确输入密码');
      return;
    }


    DioManager.getInstance().post(ServiceUrl.changePSw, {
      "verifyCode": code.toString(),
      "password": psw.toString(),
      "username": mobile.toString(),
      "type":'3'
    }, (data) async {
      RegisteEntity bannerEntity = RegisteEntity.fromJson(jsonDecode(data));
      ToastUtil.show(bannerEntity.msg);
      if (bannerEntity.code == 200) {
        if (_timer != null) {
          _timer!.cancel();
        }
        _getUserBinding();
      }
    }, (error) {
      ToastUtil.show(error);
    });
  }


  void _getDelBinding(type){
    DioManager.getInstance().post(ServiceUrl.getDelBinding,{
      "binding_type":type,
      "user_name":UserUtil.getUSER()?.userName.toString(),
    }, (data) async {
      SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
      ToastUtil.show(bannerEntity.msg);
      if(bannerEntity.code==200){
        _getUserBinding();
      }else{

      }
    }, (error) {
      ToastUtil.show(error);
    });
  }
  _getCode() {
    if (countTime != 60) {
      return;
    }
    if (mobile.isEmpty || mobile.length < 11) {
      ToastUtil.show('请正确输入手机号');
      return;
    }
    DioManager.getInstance().post(
        ServiceUrl.loginCode, {'code_type': '3', 'mobile': mobile.toString()},
            (data) async {
          SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
          if(bannerEntity.code!=200){
            ToastUtil.show(bannerEntity.msg);
          }else{
            _countTime();
          }
          update();
        }, (error) {
      ToastUtil.show(error);
    });
  }


  void _bindAuth() async {
    https://authweb.alipay.com/auth?auth_type=PURE_OAUTH_SDK&app_id=2016051801417322&scope=auth_user&state=init
    String aa = "https://authweb.alipay.com/auth?auth_type=PURE_OAUTH_SDK&app_id=2021004114617108&scope=auth_user";
    print(aa);

    Tobias tobias = Tobias();
    tobias.aliPayVersion.then((value) {
      print('~~~~~~~@@@@@@@');
      print(value);
    });
    tobias.auth(aa).catchError((eee){
      print('~~~~~~~~~~~~~~~~');
      print(eee);
    }).then((value)  {
      print('--------------------------');
      print(value);
    });
  }

  var timeTip = '获取验证码'.obs ;
  Timer? _timer;
  int countTime = 60;
  String code = '';
  String psw1 ='';
  String psw2 ='';
  void _countTime() {
    _timer = Timer.periodic(const Duration(milliseconds: 1000), (timer) {
      countTime--;
      if (countTime == 0) {
        _timer?.cancel();
        countTime = 60;
        timeTip.value = '重新获取' ;
      } else {
        timeTip.value = '重新获取${countTime}S';
      }
      print('  timeTip.value=='+  timeTip.value);
      update();
    });
  }


}

class BindAccountPage extends GetView<PayController>  {

  late PayController controller ;
  late BuildContext context ;
  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<PayController>(() => PayController());
    controller = Get.find();
    context = context1;

    return GetBuilder<PayController>(
      builder: (_){
        return  Scaffold(
            appBar: MyAppBar(context: context, title: '账号设置',hasLeading: true,),
            backgroundColor: Color(0xFFF7F8FC),
            body: _content());
      },
    );
  }

  Future<Future<int?>> _showBindInfo(type) async {
    controller.zfb_num = '';
    controller.name = '';
    controller.id_card = '';
    return showModalBottomSheet<int>(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {

        return AnimatedPadding(
          padding: MediaQuery.of(context).viewInsets,
          duration: const Duration(milliseconds: 20),
          child:  Container(
            clipBehavior: Clip.antiAlias,
            decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20.0),
                topRight: Radius.circular(20.0),
              ),
            ),
            height: type==3?350.h:300.h,
            child: Column(children: [
              SizedBox(
                height: 50,
                child: Stack(
                  textDirection: TextDirection.rtl,
                  children: [
                    const Center(
                      child: Text(
                        '绑定账号',
                        style: TextStyle(
                          fontSize: 15,
                          color: Color(0xFF333333),
                        ),
                      ),
                    ),
                    IconButton(
                        icon: Icon(Icons.close),
                        onPressed: () {
                          Navigator.of(context).pop();
                        }),
                  ],
                ),
              ),
              Container(
                  width: MediaQuery.of(context).size.width,
                  alignment: Alignment.center,
                  child: Column(
                    children: [
                      SizedBox(
                        height: 12.h,
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            '姓名：',
                            style: TextStyle(
                                color: Color(0xFF333333), fontSize: 14.sp),
                          ),
                          SizedBox(width: 25.w,),
                          Container(
                            height: 38.h,
                            width: 230.w,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4.r),
                                border: Border.all(
                                    width: 1.w, color: Color(0xFFE4E4E4))),
                            child: AccountEdit2Text(
                              //获取返回的输入内容
                              hitText: '请输入姓名',
                              icon: '',
                              contentStrCallBack: (content) {
                                controller.name = content;
                              },
                              key: ValueKey('phone'),
                            ),
                          )
                        ],
                      ),
                      SizedBox(height: 10.h,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            '身份证号：',
                            style: TextStyle(
                                color: Color(0xFF333333), fontSize: 14.sp),
                          ),
                          Container(
                            height: 38.h,
                            width: 230.w,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4.r),
                                border: Border.all(
                                    width: 1.w, color: Color(0xFFE4E4E4))),
                            child: AccountEdit2Text(
                              //获取返回的输入内容
                              hitText: '请输入身份证号',
                              icon: '',
                              contentStrCallBack: (content) {
                                controller.id_card = content;
                              },
                              key: ValueKey('phone'),
                            ),
                          )
                        ],
                      ),
                      SizedBox(height: 10.h,),
                      type=='2'?
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            '支付宝号：',
                            style: TextStyle(
                                color: Color(0xFF333333), fontSize: 14.sp),
                          ),
                          Container(
                            height: 38.h,
                            width: 230.w,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4.r),
                                border: Border.all(
                                    width: 1.w, color: Color(0xFFE4E4E4))),
                            child: AccountEdit2Text(
                              //获取返回的输入内容
                              hitText: '请输入支付宝',
                              icon: '',
                              contentStrCallBack: (content) {
                                controller.zfb_num = content;
                              },
                              key: ValueKey('phone'),
                            ),
                          )
                        ],
                      ):
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '银行卡号：',
                    style: TextStyle(
                        color: Color(0xFF333333), fontSize: 14.sp),
                  ),
                  Container(
                    height: 38.h,
                    width: 230.w,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(4.r),
                        border: Border.all(
                            width: 1.w, color: Color(0xFFE4E4E4))),
                    child: AccountEdit2Text(
                      //获取返回的输入内容
                      hitText: '请输入银行卡',
                      icon: '',
                      contentStrCallBack: (content) {
                        controller.bank_card = content;
                      },
                      key: ValueKey('phone'),
                    ),
                  )
                ],
              ),
                      SizedBox(height: 10.h,),
                      type!='2'?
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            '开户行：',
                            style: TextStyle(
                                color: Color(0xFF333333), fontSize: 14.sp),
                          ),
                          SizedBox(width: 10.w,),
                          Container(
                            height: 38.h,
                            width: 230.w,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4.r),
                                border: Border.all(
                                    width: 1.w, color: Color(0xFFE4E4E4))),
                            child: AccountEdit2Text(
                              //获取返回的输入内容
                              hitText: '请输入开户行',
                              icon: '',
                              contentStrCallBack: (content) {
                                controller.bank_name = content;
                              },
                              key: ValueKey('phone'),
                            ),
                          )
                        ],
                      ):Container(),
                      InkWell(
                          onTap: () {

                            if(controller.name.isEmpty){
                              ToastUtil.show('请输入姓名');
                              return;
                            }
                            if(controller.id_card.isEmpty){
                              ToastUtil.show('请输入身份证号');
                              return;
                            }
                            if(type=='2'){
                              if(controller.zfb_num.isEmpty){
                                ToastUtil.show('请输入支付宝号');
                                return;
                              }else{
                                controller._bindAlipay();
                              }
                            }else{

                              if(controller.bank_card.isEmpty){
                                ToastUtil.show('请输入银行卡号');
                                return;
                              }
                              if(controller.bank_name.isEmpty){
                                ToastUtil.show('请输入开户行');
                                return;
                              }
                              controller._bindBank();
                            }


                            Navigator.pop(context);
                          },
                          child: Container(
                            margin: EdgeInsets.only(top: 40.h),
                            height: 42.h,
                            width: MediaQuery.of(context).size.width - 64.w,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                color: Color(0xFF007BE5),
                                borderRadius: BorderRadius.circular(8.r)),
                            child: Text(
                              '绑定',
                              style:
                              TextStyle(fontSize: 14.sp, color: Colors.white),
                            ),
                          ))
                    ],
                  ),
                ),
            ]),
          ),
        );
      },
    );
  }


  Widget _content(){
    return SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.only(left: 20.w,right: 27.w),
          child: Column(
            children: [
              SizedBox(height: 24.h,),
              Container(
                  padding: EdgeInsets.only(left: 16.w,right: 16.w),
                  height: 52.h,
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(10.r)
                  ),
                  child:  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(controller.zfb.isEmpty?'绑定的支付宝账号':controller.zfb,style: TextStyle(
                          color: Color(0xFF999999),
                          fontSize: 13.sp
                      ),),
                      InkWell(
                          onTap: (){
                            if(Common.checkReal(context)){
                              if(controller.zfb.isEmpty){
                                _showBindInfo('2');
                                // controller._bindAuth();
                              }else{
                                _showDelte('2');
                              }
                            }

                          },
                          child:  Text(controller.zfb.isEmpty?'去绑定':'解绑',style: TextStyle(
                              color: Color(0xFFFF0000),
                              fontSize: 13.sp
                          ),)
                      )
                      ,
                    ],
                  )
              ),

              Container(
                  margin: EdgeInsets.only(top: 8.h),
                  padding: EdgeInsets.only(left: 16.w,right: 16.w),
                  height: 52.h,
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(10.r)
                  ),
                  child:  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text( controller.bank.isEmpty?'绑定的银行卡账号':controller.bank,style: TextStyle(
                          color: Color(0xFF999999),
                          fontSize: 13.sp
                      ),),

                      InkWell(
                        onTap: (){
                          if(Common.checkReal(context)){
                            if(controller.bank.isEmpty){
                              _showBindInfo(3);
                            }else{
                              _showDelte('3');
                            }
                          }

                        },
                        child:   controller.bank.isEmpty?
                        Text('去绑定',style: TextStyle(
                            color: Color(0xFFFF0000),
                            fontSize: 13.sp
                        ),):  Text('解绑',style: TextStyle(
                            color: Color(0xFFFF0000),
                            fontSize: 13.sp
                        ),)
                      )
                    ,
                    ],
                  )
              ),
              Container(
                margin: EdgeInsets.only(top: 18.h),
                alignment: Alignment.centerLeft,
                child:  Text('支付密码设置'),
              ),

              Container(
                  margin: EdgeInsets.only(top: 8.h),
                  padding: EdgeInsets.only(left: 16.w,right: 16.w),
                  height: 52.h,
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(10.r)
                  ),
                  child:  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(controller.isPsw?'******':'请设置支付密码',style: TextStyle(
                          color: Color(0xFF999999),
                          fontSize: 13.sp
                      ),),
                      InkWell(
                        onTap: (){
                          _showPsw();
                        },
                        child: Text(controller.isPsw?'修改': '设置',style: TextStyle(
                            color: Color(0xFFFF0000),
                            fontSize: 13.sp
                        ),)
                      )
                      ,
                    ],
                  )
              )

            ],
          ),
        )
    ) ;
  }

  Future<Future<int?>> _showPsw() async {
    return showModalBottomSheet<int>(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return  AnimatedPadding(
            padding: MediaQuery.of(context).viewInsets, // 我们可以根据这个获取需要的padding
            duration: const Duration(milliseconds: 100),
            child: Container(
              clipBehavior: Clip.antiAlias,
              decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(20.0),
                  topRight: Radius.circular(20.0),
                ),
              ),
              height: MediaQuery.of(context).size.height / 2.0,
              child: Column(children: [
                SizedBox(
                  height: 50,
                  child: Stack(
                    textDirection: TextDirection.rtl,
                    children: [
                      const Center(
                        child: Text(
                          '支付密码',
                          style: TextStyle(
                            fontSize: 15,
                            color: Color(0xFF333333),
                          ),
                        ),
                      ),
                      IconButton(
                          icon: Icon(Icons.close),
                          onPressed: () {
                            if( controller._timer!=null){
                              controller._timer?.cancel();
                            }

                            Navigator.of(context).pop();
                          }),
                    ],
                  ),
                ),
                Expanded(
                  child: Container(
                    width: MediaQuery.of(context).size.width,
                    alignment: Alignment.center,
                    child: Column(
                      children: [
                        SizedBox(
                          height: 12.h,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              '手机号：',
                              style: TextStyle(
                                  color: Color(0xFF333333), fontSize: 14.sp),
                            ),
                            Container(
                              height: 38.h,
                              width: 230.w,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(4.r),
                                  border: Border.all(
                                      width: 1.w, color: Color(0xFFE4E4E4))),
                              child: AccountEdit2Text(
                                //获取返回的输入内容
                                hitText: '请输入',
                                icon: '',
                                defaultText: UserUtil.getUSER()!.mobile,
                                contentStrCallBack: (content) {
                                  controller.mobile = content;
                                },
                                key: ValueKey('phone'),
                              ),
                            )
                          ],
                        ),
                        SizedBox(
                          height: 12.h,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            SizedBox(
                              width: 5.w,
                            ),
                            Text(
                              '验证码：',
                              style: TextStyle(
                                  color: Color(0xFF333333), fontSize: 14.sp),
                            ),
                            SizedBox(width: 5.w,),
                            Container(
                              height: 38.h,
                              width: 149.w,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(4.r),
                                  border: Border.all(
                                      width: 1.w, color: Color(0xFFE4E4E4))),
                              child: AccountEdit2Text(
                                //获取返回的输入内容
                                hitText: '请输入',
                                icon: '',
                                contentStrCallBack: (content) {
                                  controller.code= content;
                                },
                                key: ValueKey('newphone'),
                              ),
                            ),

                            InkWell(
                                onTap: (){
                                  controller._getCode();
                                  // controller._countTime();
                                },
                                child: Container(
                                    margin: EdgeInsets.only(left: 10.w),
                                    width: 74.w,
                                    height: 38.h,
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                      color: Color(0xFF007BE5),
                                      borderRadius: BorderRadius.circular(4.r),
                                    ),
                                    child: Obx(() =>
                                        Text(
                                          controller.timeTip.value,
                                          style:
                                          TextStyle(color: Colors.white, fontSize: 11.sp),
                                        ),
                                    ))
                            )
                            ,
                          ],
                        ),
                        SizedBox(
                          height: 12.h,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              '支付密码：',
                              style: TextStyle(
                                  color: Color(0xFF333333), fontSize: 14.sp),
                            ),
                            Container(
                                height: 38.h,
                                width: 230.w,
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(4.r),
                                    border: Border.all(
                                        width: 1.w, color: Color(0xFFE4E4E4))),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Container(
                                        height: 38.h,
                                        width: 150.w,
                                        child: AccountEdit2Text(
                                          //获取返回的输入内容
                                          hitText: '请输入',
                                          icon: '',
                                          contentStrCallBack: (content) {
                                            controller.psw = content;
                                          },
                                          key: ValueKey('phone'),
                                        )),
                                    // Container(
                                    //   margin: EdgeInsets.only(right: 16.w),
                                    //   child: Image.asset(
                                    //     '${Constant.IMG_BASE}eye_close.png',
                                    //     width: 17.w,
                                    //     height: 11.h,
                                    //   ),
                                    // )
                                  ],
                                ))
                          ],
                        ),
                        SizedBox(
                          height: 12.h,
                        ),
                        InkWell(
                            onTap: () {
                              controller._bindPsw();
                            },
                            child: Container(
                              margin: EdgeInsets.only(top: 30.h),
                              height: 42.h,
                              width: MediaQuery.of(context).size.width - 64.w,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  color: Color(0xFF007BE5),
                                  borderRadius: BorderRadius.circular(8.r)),
                              child: Text(
                                '确定',
                                style:
                                TextStyle(fontSize: 14.sp, color: Colors.white),
                              ),
                            ))
                      ],
                    ),
                  ),
                ),
              ]),
            ));
      },
    );
  }

  _showDelte(type){
    String msg = '';
    if(type =='2'){
      msg = '确定解绑(${controller.zfb})吗？解绑后将无法使用该账号提现';
    }
    if(type =='3'){
      msg = '确定解绑(${controller.bank})吗？解绑后将无法使用该账号提现';
    }
    showDialog(context: context, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){
          // if(type =='2'){
           controller. _getDelBinding(type);
          // }
          Navigator.pop(context1);

        }
      },
        title: '解绑账号',
        msg: msg+'',
        sureText: '确定',
        cancelText: '暂不',

      );
    },
    );
  }


}
